package com.vnaloha.common.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.vnaloha.common.model.Product;
import com.vnaloha.common.service.CategoryService;
import com.vnaloha.common.service.ManufacturerService;
import com.vnaloha.common.service.ProductService;

@Controller
@RequestMapping("admin")
public class AdminController {
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private ManufacturerService manufacturerService;
	
	@RequestMapping(method = RequestMethod.GET)
	public String index() {
		return "admin/index";
	}
	
	@RequestMapping(value = "user", method = RequestMethod.GET)
	public String getListUser() {
		return "admin/user";
	}
	@RequestMapping(value = "manageproduct", method = RequestMethod.GET)
	public String manageProduct(ModelMap modelMap) {
		
		modelMap.addAttribute("listProduct", productService.list());
		return "admin/manageProduct";
	}
			
	@RequestMapping(value = "/product-update/{productID}", method = RequestMethod.GET)
	public String saveUpdate(@PathVariable("productID") Integer productID,ModelMap modelMap) {
		
		modelMap.addAttribute("product", productService.get(productID));
		modelMap.addAttribute("listCategory",categoryService.list());
		modelMap.addAttribute("listManufacturer", manufacturerService.list());
		return "admin/saveUpdateProduct";
	}
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String updateUser(@ModelAttribute("product") @Valid Product product, BindingResult result) {
		if(result.hasErrors()) {
			return "/product-update";
		} else {
			productService.update(product);
			return "redirect:/admin/manageproduct";
		}
	}
	
}
